/* File Created: April 8, 2013 */
/**
 *
 * Phonegap share plugin for Android
 * Kevin Schaul 2011
 *
 */

var Share = function () {};

Share.prototype.show = function (content, success, fail) {
	return cordova.exec(function (args) {
		success(args);
	}, function (args) {
		fail(args);
	}, 'Share', '', [content]);
};

if (!window.plugins) {
	window.plugins = {};
}
if (!window.plugins.share) {
	window.plugins.share = new Share();
}
var share = function () {
    var facebookWith = function (picture, name, caption, description, link) {
        cordova.exec(function (result) {
                     //success callback, do something here
                     },
                     function (error) {
                     //failed callback, do something here
                     },
                     "FaceBookPlugIn",
                     "shareImageWith", [picture, name, caption, description, link, "facebook"]);
    };
    var twitterWith = function (picture, name, caption, description, link) {
        cordova.exec(function (result) {
                     //success callback, do something here
                     },
                     function (error) {
                     //failed callback, do something here
                     },
                     "FaceBookPlugIn",
                     "shareImageWith", [picture, name, caption, description, link, "twitter"]);
    };
    var getBrightness = function (callback) {
        cordova.exec(function (result) {
                     //success callback, do something here
                     callback(parseFloat(result));
                     },
                     function (error) {
                     //failed callback, do something here
                     },
                     "FaceBookPlugIn",
                     "getBrightness", []);
    };
    var setBrightness = function (value) {
        cordova.exec(function (result) {
                     //success callback, do something here
                     },
                     function (error) {
                     //failed callback, do something here
                     },
                     "FaceBookPlugIn",
                     "setBrightness", [value]);
    };
    var shareLinkedIn = function(strBookId, strThumbnailMedium){
        var linkedinAccessToken = localStore.get("linkedinAccessToken");
        if (linkedinAccessToken && linkedinAccessToken.length > 0){
            /* exist access token */
            showLoadingDialog();
            $.ajax({
                   url : 'https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='+linkedinAccessToken,
                   type: 'post',
                   headers : {
                   'Content-Type'  : 'application/json',
                   'x-li-format'   : 'json'
                   },
                   data: JSON.stringify({
                                        
                                        "content": {
                                        "title": "getAbstract",
                                        "submitted-url": 'http://www.getabstract.com/ShowAbstract.do?dataId=' + strBookId,
                                        "submitted-image-url": strThumbnailMedium
                                        },
                                        "visibility": {
                                        "code": "anyone"
                                        }
                                        }),
                   success: function(a){
                   showPopup(getLocalizeText('successfullyPosted'));
                   hideLoadingDialog();
                   
                   },
                   error: function(a){
                   showPopup(getLocalizeText('failed'));
                   localStore.save("linkedinAccessToken", null);
                   hideLoadingDialog();
                   }
                   })
            return;
        }
        
        
        ref = window.open('https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=77p5ia6yueohz5&scope=rw_nus&state=5cHBB8OdnHSPyOUO&redirect_uri=http://www.getabstract.com/social-confirmation','_blank','location=no');
        ref.addEventListener('loadstart', function(e){
                             if(e.url.indexOf('?code=') >=0 ){
                             if(e.url.match(/=[^]+&/)){
                             var code = e.url.match(/=[^]+&/)[0].substring(1).replace('&','');
                             window.sessionStorage.setItem('code', code);
                             ref.close();
                             console.log('code :' + code);
                             $.ajax({
                                    url: 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+code+'&redirect_uri=http://www.getabstract.com/social-confirmation&client_id=77p5ia6yueohz5&client_secret=5cHBB8OdnHSPyOUO',
                                    success: function(a){
                                    localStore.save("linkedinAccessToken", a.access_token);
                                    $.ajax({
                                           url : 'https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='+a.access_token,
                                           type: 'post',
                                           headers : {
                                           'Content-Type'  : 'application/json',
                                           'x-li-format'   : 'json'
                                           },
                                           data: JSON.stringify({
                                                                
                                                                "content": {
                                                                "title": "getAbstract",
                                                                "submitted-url": 'http://www.getabstract.com/ShowAbstract.do?dataId=' + strBookId,
                                                                "submitted-image-url": strThumbnailMedium
                                                                },
                                                                "visibility": {
                                                                "code": "anyone"
                                                                }
                                                                }),
                                           success: function(a){
                                           showPopup(getLocalizeText('successfullyPosted'));
                                           
                                           },
                                           error: function(a){
                                           showPopup(getLocalizeText('failed'));
                                           localStore.save("linkedinAccessToken", null);
                                           
                                           }
                                           })
                                    },
                                    error: function(a){
                                    showPopup(getLocalizeText('failed'));
                                    localStore.save("linkedinAccessToken", null);
                                    }
                                    })
                             }
                             }
                             });
        
    };
    var loginWithSSO = function(strEmail, successCallback){
        //http://int.getabstract.com/api/oauth/sso_confirmation or http://www.getabstract.com/api/oauth/sso_confirmation still pending. Need to research more
        ref = window.open(localStore.get(strDomainKey)+'api/oauth/sso?client_id=getabstract-mobile-native-app&response_type=token&redirect_uri=getabstractapp.mobile&login_hint='+strEmail,'_blank','location=no');
        ref.addEventListener('loadstart', function(e){
                             if(e.url.indexOf('#access_token') >=0 ){
                                 /* success case */
                                 if(e.url.match(/#[^]+&/)){
                                     var strResult1 = e.url.match(/#[^]+&/) + '';
                                     strResult1 = strResult1.substring(1, strResult1.length - 1);
                                     /* convert strResult1 to object data */
                                     var arrayOfStrings = strResult1.split('&');
                                     var strAccessTokenTemp = '';
                                     var strRefreshTokenTemp = '';
                                     if (arrayOfStrings.length > 0){
                                         strAccessTokenTemp = arrayOfStrings[0].replace('access_token=', '');
                                     
                                     }
                                     if (arrayOfStrings.length > 1){
                                         strRefreshTokenTemp = arrayOfStrings[1].replace('refresh_token=', '');
                                     
                                     }
                                     
                                     if (strAccessTokenTemp.length > 0 && strRefreshTokenTemp.length > 0){
                                         /* get token success */
                                         var user = new UserModel();
                                         
                                         user.accessToken(strAccessTokenTemp);
                                         user.refreshToken(strRefreshTokenTemp);
                                         
                                         
                                         successCallback(user);
                                     }
                                     else{
                                         /* show error alert */
                                         ShowErrorMessage(null);
                                     }
                                     ref.close();
                                 }
                             }
                             else if (e.url.indexOf('#error=') >=0){
                                 /* failed case */
                                 if(e.url.match(/#[^]+/)){
                                     var strResult1 = e.url.match(/#[^]+/) + '';
                                     strResult1 = strResult1.substring(1);
                                     
                                     /* convert strResult1 to object data */
                                     var arrayOfStrings = strResult1.split('&');
                                     var strErrorMessage = '';
                                     if (arrayOfStrings.length > 1){
                                         strErrorMessage = arrayOfStrings[1].replace('error_description=', '');
                                     }
                                     if(strErrorMessage.length > 0){
                                         /* show error message */
                                         strErrorMessage = decodeURIComponent(strErrorMessage);
                                         strErrorMessage = strErrorMessage.replace(/\+/g, ' ');
                                         ShowErrorMessage(strErrorMessage);
                                     }
                                     else{
                                         ShowErrorMessage(null);
                                     }
                                     ref.close();
                                 }
                             }
                             
                             });
        
        
        
    };
    return {
        facebookWith: facebookWith,
        twitterWith: twitterWith,
        getBrightness: getBrightness,
        setBrightness: setBrightness,
        shareLinkedIn: shareLinkedIn,
        loginWithSSO: loginWithSSO
    };
    
}()